<?php

namespace app\api\controller;

use think\Controller;
use think\facade\Request;
use think\DB;
use app\model\Order as OrderDB;
use app\model\MemberBuyerCancelOrder;
use app\model\MemberBuyerPlatformInfo;
use app\model\MemberBuyerInfo;
use think\Validate;
use think\facade\Config;


class Order extends Controller
{

    public function getMyOrderList()
    {
        $orderData = OrderDB::getList([
            ['receiverid', '=', session('memberInfo.userid')],
            ['status', 'in', Request::get('status', 99)]
        ]);
        return json(['code' => 0, 'data' => $orderData]);
    }

    public function accept()
    {
        $platform = MemberBuyerPlatformInfo::where('userid', session('memberInfo.userid'))->find();

        if (!$platform || $platform['status'] != 1 && Request::post('isaccept') == 1) {
            return json(['code' => 4031, 'msg' => lang(4031)]);
        }

        $dbms = Config::get('database.type');
        $host = Config::get('database.hostname');
        $dbName = Config::get('database.database');
        $user = Config::get('database.username');
        $pass = Config::get('database.password');
        $dsn = "$dbms:host=$host;dbname=$dbName";

        try {
            $dbh = new \PDO($dsn, $user, $pass);
        } catch (PDOException $e) {
            die("Error!: " . $e->getMessage() . "<br/>");
        }

        $stmt = $dbh->prepare("CALL UserGetOrder(" . session('memberInfo.userid') . ")");
        $stmt->execute();
        $row = $stmt->fetch();

        $msg = [
            '0' => '',
            '1' => '无匹配订单',
            '11' => '用户不存在',
            '12' => '账号被禁用',
            '13' => '未绑定（或未审核通过）平台账号',
            '21' => '已有待操作的订单',
            '31' => '本日已接订单超过4单',
            '32' => '本周已接订单超过20',
            '33' => '本月已接订单超过80',
        ];
        $row['msg'] = $msg[$row['errcode']];

        return json(['code' => 0, 'data' => $row]);
    }

    function jieqv($str)
    {

        $st = '';
        $strlen = mb_strlen($str);

        for ($i = 0; $i < $strlen; $i++) {
            if ($i % 2 == 0) {
                $st .= mb_substr($str, $i, 1, 'utf8');
            } else {
                $st .= '*';
            }
        }
        return $st;
    }


    public function accept_sure_if()
    {
        $platform = MemberBuyerPlatformInfo::where('userid', session('memberInfo.userid'))->find();

        if (!$platform || $platform['status'] != 1 && Request::post('isaccept') == 1) {
            return json(['code' => 4031, 'msg' => lang(4031)]);
        }

        $dbConfig = DB::getConfig();
        $dbConfig['params'] = [\PDO::ATTR_EMULATE_PREPARES => true];
        $resultSet = DB::connect($dbConfig)->query("CALL UserGetPreOrder(" . session('memberInfo.userid') . ")")[0][0];

        if (isset($resultSet['title'])) {
            $resultSet['title'] = $this->jieqv($resultSet['title']);
        }

        $msg = [
            '0' => '',
            '1' => '无匹配订单',
            '11' => '用户不存在',
            '12' => '账号被禁用',
            '13' => '未绑定（或未审核通过）平台账号',
            '21' => '已有待操作的订单',
            '31' => '本日已接订单超过5单',
            '32' => '本周已接订单超过20',
            '33' => '本月已接订单超过80',
        ];
        if (isset($resultSet['errcode'])) {
            $resultSet['msg'] = $msg[$resultSet['errcode']];
        } else {
            return json(['code' => 0, 'data' => [
                'errcode' => 2,
                'msg' => "错误信息:" . json_encode($resultSet)
            ]]);
        }


        return json(['code' => 0, 'data' => $resultSet]);
    }

    public function getCount()
    {
        $orderData[1] = OrderDB::where([
            ['receiverid', '=', session('memberInfo.userid')],
            ['status', 'between', '2,5']
        ])->count();
        $orderData[2] = OrderDB::where([
            ['receiverid', '=', session('memberInfo.userid')],
            ['status', 'in', '6,20']
        ])->count();
        $orderData[3] = DB::name('member_buyer_cancel_order')->where([
            ['userid', '=', session('memberInfo.userid')]
        ])->count();
        return json(['code' => 0, 'data' => $orderData]);
    }
    public function getUndoneOrder()
    {
        $orderData = OrderDB::getList([
            ['receiverid', '=', session('memberInfo.userid')],
            ['status', 'between', '2,5']
        ]);
        return json(['code' => 0, 'data' => $orderData]);
    }

    public function getCompletedOrder()
    {
        $orderData = OrderDB::getList([
            ['receiverid', '=', session('memberInfo.userid')],
            ['status', 'in', '6'],
        ]);
        return json(['code' => 0, 'data' => $orderData]);
    }

    public function getRevokedOrder()
    {
        $orderData = MemberBuyerCancelOrder::field('taskid,orderid,cancel_at,type')->where('userid', session('memberInfo.userid'))
            ->order('cancel_at desc')->paginate(20);

        foreach ($orderData as &$vo) {
            $vo['imgurl'] = $vo->task['imgurl'];
            $vo['buyprice'] = $vo->task['buyprice'];
            $vo['commission'] = $vo->order['commission'];
            $vo['shop_deposit'] = $vo->order['shop_deposit'];
            $vo['date'] = substr($vo['cancel_at'], 0, 16);
            unset($vo->order);
            unset($vo->task);
        }
        return json(['code' => 0, 'data' => $orderData]);
    }

    public function getDetail()
    {
        $orderData = OrderDB::where('receiverid', session('memberInfo.userid'))
            ->where('orderid', Request::get('orderid'))
            ->find();
        if (!$orderData) {
            return json(['code' => 1, 'msg' => '没有找到该订单']);
        }
        $orderData->task;
        $orderData->task['hideShopname'] = $orderData->task['hideShopname'];
        $orderData->taskInfo;
        return json([
            'code' => 0,
            'data' => $orderData
        ]);
    }

    public function getPreDetail()
    {
        $orderData = OrderDB::where('prereceiverid', session('memberInfo.userid'))
            ->where('orderid', Request::get('orderid'))
            ->find();
        if (!$orderData) {
            return json(['code' => 1, 'msg' => '没有找到该订单']);
        }
        $orderData->task;
        $orderData->task['hideShopname'] = $orderData->task['hideShopname'];
        $orderData->taskInfo;
        return json([
            'code' => 0,
            'data' => $orderData
        ]);
    }


    public function doOrder()
    {
        $orderData = OrderDB::where('receiverid', session('memberInfo.userid'))
            ->where('orderid', '=', Request::post('orderid'))
            ->where('status', 'between', '2,5')
            ->find();
        if (!$orderData) {
            return json(['code' => 1, 'msg' => '找不到可操作任务']);
        }

        $validate = Validate::make([
            'status' => 'in:3,5',
        ]);


        $postData = Request::post('');
        if (!$validate->check($postData)) {
            return json([
                'code' => 1,
                'msg' => $validate->getError()
            ]);
        }
        $msg = [
            'imgurl1.require' => '请先上传搜索页结果截图',
            'imgurl2.require' => '请先上传货比一家截图',
            // 'imgurl3.require' => '请先上传任意商品2截图',
            'imgurl4.require' => '请先上传目标店铺另外商品截图',
            // 'imgurl5.require' => '请先上传店铺商品2截图',
            // 'imgurl6.require' => '请先上传目标商品头部截图',
            'imgurl7.require' => '请先上传目标商品尾部截图',
            'imgurl8.require' => '请先上传聊天页面截图',
            'imgurl9.require' => '请先上传付款页面截图',
            'imgurl10.require' => '请先上传任务好评1截图',
            'imgurl11.require' => '请先上传任务好评2截图',
            'imgurl12.require' => '请先上传收藏店铺截图',
            'imgurl13.require' => '请先上传收藏宝贝截图',
            'platform_orderid.require' => '请填写淘宝订单编号',
            'advancepayment.require' => '请填写实付金额',
        ];
        if (Request::post('status') == 3) {
            if ($orderData->task['isnoscreenshot'] == 1) {
                $make = [
                    'imgurl9' => 'require',
                    'platform_orderid' => 'require',
                    'advancepayment' => 'require',
                ];
            } else {
                $make = [
                    'imgurl1' => 'require',
                    'imgurl2' => 'require',
                    // 'imgurl3' => 'require',
                    'imgurl4' => 'require',
                    // 'imgurl5' => 'require',
                    // 'imgurl6' => 'require',
                    'imgurl7' => 'require',
                    // 'imgurl8' => 'require',
                    'imgurl9' => 'require',
                    'platform_orderid' => 'require',
                    'advancepayment' => 'require',
                ];
                if ($orderData->task['ischat']) {
                    $make['imgurl8'] = 'require';
                }
                if ($orderData->task['iscollectionshop']) {
                    $make['imgurl12'] = 'require';
                }
                if ($orderData->task['iscollectionproduct']) {
                    $make['imgurl13'] = 'require';
                }

            }

            $totime = strtotime($orderData['receive_time']) + 10 * 60;
            if (time() - $totime < 0) {
                return json([
                    'code' => 1,
                    'msg' => '放慢步调 ,请 ' . \tool\Date::countdown($totime) . ' 后提交'
                ]);
            }

            $validate2 = Validate::make($make)->message($msg);
            if (!$validate2->check($orderData)) {
                return json([
                    'code' => 1,
                    'msg' => $validate2->getError()
                ]);
            } else {
                if (!$orderData['complete_time']) {
                    $postData['complete_time'] = \tool\Date::date();
                }
            }
            if ($orderData->getData('status') == 2) {
                DB::name('task')->where('taskid', $orderData['taskid'])->dec('notoperatednum')->inc('notdeliverynum')->update();
            }
        }

        if (Request::post('status') == 5) {
            if ($orderData->task['isnoscreenshot'] == 1) {
                $make = [];
            } else {
                $make = [
                    'imgurl10' => 'require',
                    'imgurl11' => 'require',
                ];
            }

            $validate2 = Validate::make($make)->message($msg);
            if (!$validate2->check($orderData)) {
                return json([
                    'code' => 1,
                    'msg' => $validate2->getError()
                ]);
            } else {
                if (!$orderData['evaluation_time']) {
                    $postData['evaluation_time'] = \tool\Date::date();
                }
            }
            if ($orderData->getData('status') == 4) {
                DB::name('task')->where('taskid', $orderData['taskid'])->dec('notevaluationnum')->inc('notconfirmnum')->update();
            }

        }

        if (Request::has('advancepayment', 'post')) {
            if (Request::post('advancepayment') > $orderData->task['buyprice'] * $orderData->task['buycount'] + 20) {
                return json([
                    'code' => 1,
                    'msg' => '付款金额超出范围'
                ]);
            }
            // if (Request::post('advancepayment') > ($orderData->task['buyprice'] + 10) && Request::post('advancepayment') < $orderData->task['buyprice']) {
            //     return json([
            //         'code' => 1,
            //         'msg' => '实际付款金额不在范围' . $orderData->task['buyprice'] . ' ~ ' . ($orderData->task['buyprice'] + 10)
            //     ]);
            // }
        }
        $affectedRows = $orderData->allowField([
            'imgurl1',
            'imgurl2',
            'imgurl3',
            'imgurl4',
            'imgurl5',
            'imgurl6',
            'imgurl7',
            'imgurl8',
            'imgurl9',
            'imgurl10',
            'imgurl11',
            'platform_orderid',
            'advancepayment',
            'complete_time',
            'evaluation_time',
            'status',
        ])->where('receiverid', session('memberInfo.userid'))->where('orderid', '=', Request::post('orderid'))->update($postData);

        if ($affectedRows !== false) {
            return json(['code' => 0]);
        } else {
            return json(['code' => 1, 'msg' => '操作失败']);
        }
    }

    public function appeal_post()
    {
        $rule = [
            'orderid' => 'require',
            'content' => 'require',
        ];

        $msg = [
            'orderid.require' => '任务ID不能为空',
            'content.require' => '内容必须填写',
        ];

        $validate = Validate::make($rule)->message($msg);
        $result = $validate->check(Request::post(''));
        if (!$result) {
            return json(['code' => 1, 'msg' => $validate->getError()]);
        }

        $orderData = OrderDB::where('receiverid', session('memberInfo.userid'))
            ->where('orderid', Request::post('orderid'))
            ->where('status', 'between', '2,5')
            ->find();

        if (!$orderData) {
            return json(['code' => 1, 'msg' => '没有可申诉订单']);
        }

        $affectedRows = DB::name('appeal')->insert([
            'userid' => session('memberInfo.userid'),
            'touserid' => $orderData['shopid'],
            'ordersn' => Request::post('orderid'),
            'img1' => Request::post('img1'),
            'img2' => Request::post('img2'),
            'content' => Request::post('content'),
            'appealType' => Request::post('appealType'),
            'usertype' => 1,
        ]);
        $orderData->save([
            'appealStatus' => 1
        ]);

        if ($affectedRows !== false) {
            return json(['code' => 0]);
        } else {
            return json(['code' => 1, 'msg' => '增加失败']);
        }
    }

    public function sureOrder()
    {
        $orderData = OrderDB::where('prereceiverid', session('memberInfo.userid'))
            ->where('orderid', Request::get('orderid'))
            ->where('status', 1)
            ->find();
        if (!$orderData) {
            return json(['code' => 1, 'msg' => '可能任务已经被撤销了']);
        }

        $account = MemberBuyerPlatformInfo::where('userid', session('memberInfo.userid'))->value('account');

        $affectedRows = OrderDB::where('prereceiverid', session('memberInfo.userid'))
            ->where('orderid', Request::get('orderid'))
            ->where('status', 1)
            ->update([
                'receiverid' => session('memberInfo.userid'),
                'revaccount' => $account,
                'receive_time' => \tool\Date::date(),
                'status' => 2,
            ]);

        // $affectedRows = $orderData->save([
        //     'receiverid' => session('memberInfo.userid'),
        //     'revaccount' => $account,
        //     'receive_time' => \tool\Date::date(),
        //     'status' => 2,
        // ]);
        // $affectedRows = $orderData->save([
        //     'receiverid' => session('memberInfo.userid'),
        //     'revaccount' => $account,
        //     'receive_time' => \tool\Date::date(),
        //     'status' => 2,
        // ]);

        if ($affectedRows === false) {
            return json(['code' => 1, 'msg' => '可能任务已经被撤销了']);
        }

        DB::name('task')->where('taskid', $orderData['taskid'])->dec('notacceptnum')->inc('notoperatednum')->update();
        DB::name('autoassign_log')->insert([
            'orderid' => $orderData['orderid'],
            'taskid' => $orderData['taskid'],
            'userid' => session('memberInfo.userid')
        ]);
        return json(['code' => 0]);
    }
    public function noOrder()
    {
        $orderData = OrderDB::where('prereceiverid', session('memberInfo.userid'))
            ->where('orderid', Request::get('orderid'))
            ->where('status', 1)
            ->find();
        if ($orderData) {
            $orderData->where('prereceiverid', session('memberInfo.userid'))
                ->where('orderid', Request::get('orderid'))
                ->where('status', 1)
                ->update([
                    'prereceiverid' => 0,
                    'prereceive_time' => null,
                    'debug' => 'thinkphp',
                ]);
        }
        return json(['code' => 0]);
    }



    public function cancelOrder_post()
    {
        $orderData = OrderDB::where('receiverid', session('memberInfo.userid'))
            ->where('orderid', Request::post('orderid'))
            ->where('status', 'between', '2,3')
            ->find();
        if (!$orderData) {
            return json(['code' => 1, 'msg' => '找不到可操作任务']);
        }

        if ($orderData->getData('status') == 2) {
            DB::name('task')->where('taskid', $orderData['taskid'])->dec('notoperatednum')->inc('notacceptnum')->update();
        } else {
            DB::name('task')->where('taskid', $orderData['taskid'])->dec('notdeliverynum')->inc('notacceptnum')->update();
        }

        MemberBuyerCancelOrder::insert([
            'userid' => session('memberInfo.userid'),
            'orderid' => Request::post('orderid'),
            'taskid' => $orderData['taskid'],
            'note' => Request::post('note'),
            'catch_at' => $orderData['receive_time']
        ]);

        $orderData->save([
            'orderid' => Request::post('orderid'),
            'imgurl1' => null,
            'imgurl2' => null,
            'imgurl3' => null,
            'imgurl4' => null,
            'imgurl5' => null,
            'imgurl6' => null,
            'imgurl7' => null,
            'imgurl8' => null,
            'imgurl9' => null,
            'imgurl10' => null,
            'imgurl11' => null,
            'platform_orderid' => null,
            'advancepayment' => null,
            'receive_time' => null,
            'complete_time' => null,
            'receiverid' => null,
            'revaccount' => null,
            'status' => 1,
        ]);

        DB::name('autoassign_log')
            ->where('userid', session('memberInfo.userid'))
            ->where('orderid', Request::post('orderid'))
            ->where('status', 0)
            ->update([
                'status' => 2,
                'updatetime' => \tool\Date::date()
            ]);

        $memberBuyerInfo = MemberBuyerInfo::where('userid', session('memberInfo.userid'))->find();

        DB::name('member_buyer_score_log')->insert([
            'userid' => session('memberInfo.userid'),
            'orderid' => Request::post('orderid'),
            'prescore' => $memberBuyerInfo['score'],
            'change' => -1,
            'score' => $memberBuyerInfo['score'] - 1,
            'note' => '取消订单',
        ]);

        MemberBuyerInfo::where('userid', session('memberInfo.userid'))->setDec('score');

        return json(['code' => 0]);
    }

}
